import React, { useState, useEffect, useCallback } from 'react';
import { ScrollView, View, Text, TouchableOpacity, StyleSheet, Platform, ToastAndroid, NativeEventEmitter, NativeModules, AppState, Alert } from 'react-native';

const { AutoGoModule } = NativeModules;
const eventEmitter = new NativeEventEmitter(AutoGoModule);

const App: React.FC = () => {
  const [isEnabled, setIsEnabled] = useState(false);
  const [isRunning, setIsRunning] = useState(false);

  // -----------------------------
  // 显示 Toast
  // -----------------------------
  const showToast = useCallback((message: string, duration: number = ToastAndroid.SHORT) => {
    if (Platform.OS === 'android') {
      ToastAndroid.show(message, duration);
    } else {
      console.log(`Toast: ${message}`);
    }
  }, []);

  // -----------------------------
  // 检查无障碍权限
  // -----------------------------
  const checkAccessibilityStatus = useCallback(async () => {
    try {
      const enabled = await AutoGoModule.isAccessibilityServiceEnabled();
      setIsEnabled(enabled);
      if (enabled) showToast('无障碍权限已开启 ✓');
    } catch (error) {
      console.error('检查无障碍权限失败:', error);
      showToast('检查权限失败', ToastAndroid.LONG);
    }
  }, [showToast]);

  // -----------------------------
  // 预检权限按钮
  // -----------------------------
  const handlePreCheck = async () => {
    if (Platform.OS !== 'android') {
      Alert.alert('提示', '此功能仅支持 Android 平台');
      return;
    }

    try {
      showToast('正在检查权限...');
      const enabled = await AutoGoModule.isAccessibilityServiceEnabled();
      setIsEnabled(enabled);

      if (enabled) {
        showToast('无障碍权限已开启 ✓', ToastAndroid.LONG);
      } else {
        showToast('需要开启无障碍权限', ToastAndroid.LONG);
        Alert.alert(
          '需要无障碍权限',
          '请开启 AutoGo 的无障碍权限以使用脚本功能',
          [
            { text: '取消', style: 'cancel', onPress: () => showToast('已取消权限设置') },
            {
              text: '去开启',
              onPress: () => {
                showToast('正在跳转到无障碍设置...');
                AutoGoModule.openAccessibilitySettings();
              },
            },
          ]
        );
      }
    } catch (error) {
      console.error('预检错误:', error);
      showToast('预检失败，请重试', ToastAndroid.LONG);
    }
  };

  // -----------------------------
  // 启动脚本
  // -----------------------------
  const handleStartScript = async () => {
    if (!isEnabled) {
      showToast('请先开启无障碍权限', ToastAndroid.LONG);
      return;
    }

    if (Platform.OS !== 'android') {
      Alert.alert('提示', '此功能仅支持 Android 平台');
      return;
    }

    try {
      setIsRunning(true);
      showToast('脚本启动中...');

      await AutoGoModule.minimizeApp()
      await AutoGoModule.runActions([
        { name: 'swipeUp', delay: 1000 },
        { name: 'swipeDown', delay: 1000 },
        { name: 'click', x: 500, y: 1000, delay: 1000 },
      ]);
      
    } catch (error: any) {
      setIsRunning(false);
      const errorMessage = error.message || '启动脚本时发生错误';
      showToast(`启动失败: ${errorMessage}`, ToastAndroid.LONG);
      console.error('启动脚本错误:', error);
    }
  };

  // -----------------------------
  // App 从后台回到前台时再次检查权限
  // -----------------------------
  useEffect(() => {
    const subscription = AppState.addEventListener('change', (state) => {
      if (state === 'active') {
        checkAccessibilityStatus();
      }
    });

    return () => subscription.remove();
  }, [checkAccessibilityStatus]);

  // -----------------------------
  // 监听原生事件 onScriptFinished
  // -----------------------------
  useEffect(() => {
    const subscription = eventEmitter.addListener('onScriptFinished', () => {
      setIsRunning(false);
      showToast('脚本执行完成 ✓', ToastAndroid.LONG);
    });

    return () => subscription.remove();
  }, [showToast]);

  // -----------------------------
  // 页面渲染
  // -----------------------------
  return (
    <ScrollView contentContainerStyle={styles.scrollContainer}>
      <View style={styles.container}>
        <Text style={styles.title}>AutoGo 自动化工具</Text>

        <View style={styles.statusContainer}>
          <Text style={styles.statusLabel}>无障碍权限状态:</Text>
          <Text style={[styles.statusValue, isEnabled ? styles.statusEnabled : styles.statusDisabled]}>
            {isEnabled ? '已开启 ✓' : '未开启 ✗'}
          </Text>
        </View>

        <View style={styles.scriptStatus}>
          <Text style={styles.scriptStatusLabel}>脚本状态:</Text>
          <Text style={[styles.scriptStatusValue, isRunning ? styles.scriptRunning : styles.scriptIdle]}>
            {isRunning ? '运行中...' : '待机中'}
          </Text>
        </View>

        <View style={styles.buttonContainer}>
          <TouchableOpacity style={[styles.button, styles.preCheckButton]} onPress={handlePreCheck} disabled={isRunning}>
            <Text style={styles.buttonText}>{isEnabled ? '重新检查' : '预检权限'}</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.button, styles.startButton, (!isEnabled || isRunning) && styles.buttonDisabled]}
            onPress={handleStartScript}
            disabled={!isEnabled || isRunning}
          >
            <Text style={styles.buttonText}>{isRunning ? '执行中...' : '启动脚本'}</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.instructions}>
          <Text style={styles.instructionsTitle}>使用说明:</Text>
          <Text style={styles.instructionsText}>1. 点击"预检权限"按钮开启无障碍权限</Text>
          <Text style={styles.instructionsText}>2. 点击"启动脚本"开始自动化操作</Text>
          <Text style={styles.instructionsText}>3. 脚本执行顺序: 后台运行 → 上滑 → 下滑 → 点击</Text>
          <Text style={styles.instructionsText}>4. 运行过程中可随时点击"停止脚本"</Text>
        </View>

        <View style={styles.tips}>
          <Text style={styles.tipsTitle}>提示:</Text>
          <Text style={styles.tipsText}>• 请确保在无障碍设置中开启AutoGo服务</Text>
          <Text style={styles.tipsText}>• 脚本运行时请勿操作手机</Text>
          <Text style={styles.tipsText}>• 如遇问题请重新预检权限</Text>
        </View>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  scrollContainer: { flexGrow: 1, backgroundColor: '#f5f5f5', padding: 20, alignItems: 'center' },
  container: { width: '100%', maxWidth: 600, alignItems: 'center' },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, color: '#333', textAlign: 'center' },
  statusContainer: { flexDirection: 'row', alignItems: 'center', marginBottom: 15, padding: 12, backgroundColor: 'white', borderRadius: 8, width: '100%' },
  statusLabel: { fontSize: 16, marginRight: 10, color: '#666', flex: 1 },
  statusValue: { fontSize: 16, fontWeight: 'bold' },
  statusEnabled: { color: '#4CAF50' },
  statusDisabled: { color: '#F44336' },
  scriptStatus: { flexDirection: 'row', alignItems: 'center', marginBottom: 25, padding: 12, backgroundColor: 'white', borderRadius: 8, width: '100%' },
  scriptStatusLabel: { fontSize: 16, marginRight: 10, color: '#666', flex: 1 },
  scriptStatusValue: { fontSize: 16, fontWeight: 'bold' },
  scriptRunning: { color: '#FF9800' },
  scriptIdle: { color: '#2196F3' },
  buttonContainer: { width: '100%', marginBottom: 25 },
  button: { padding: 16, borderRadius: 8, marginVertical: 6, alignItems: 'center', justifyContent: 'center' },
  preCheckButton: { backgroundColor: '#2196F3' },
  startButton: { backgroundColor: '#4CAF50' },
  buttonDisabled: { backgroundColor: '#CCCCCC' },
  buttonText: { color: 'white', fontSize: 16, fontWeight: 'bold' },
  instructions: { backgroundColor: 'white', padding: 15, borderRadius: 8, width: '100%', marginBottom: 15, shadowColor: '#000', shadowOffset: { width: 0, height: 1 }, shadowOpacity: 0.1, shadowRadius: 2, elevation: 2 },
  instructionsTitle: { fontSize: 16, fontWeight: 'bold', marginBottom: 8, color: '#333' },
  instructionsText: { fontSize: 14, marginBottom: 4, color: '#666', lineHeight: 20 },
  tips: { backgroundColor: '#E3F2FD', padding: 15, borderRadius: 8, width: '100%', borderLeftWidth: 4, borderLeftColor: '#2196F3' },
  tipsTitle: { fontSize: 14, fontWeight: 'bold', marginBottom: 6, color: '#1976D2' },
  tipsText: { fontSize: 12, marginBottom: 3, color: '#1976D2', lineHeight: 18 },
});

export default App;
